package json

import (
	"encoding/json"
	"fmt"
)

type Address struct {
	Type    string
	City    string
	Country string
}

type VCard struct {
	FirstName string
	LastName  string
	Addresses []*Address
	Remark    string
}

func FmtJson()  {
	Example1()
	Example2()
}

/*
 * 解析json案例1
 */
func Example1() {

	fmt.Println("解析json案例1")

	b := []byte(`{"Name": "Wednesday", "Age": "6", "Parents": ["Gomez", "Morticia"]}`)
	var f interface{}
	err := json.Unmarshal(b, &f)

	if err != nil {
		fmt.Println(err)
	}

	m := f.(map[string]interface{})

	for k, v := range m {
		switch vv := v.(type) {
		case string:
			fmt.Println(k, "is string", vv)
		case int:
			fmt.Println(k, "is int", vv)
		case []interface{}:
			fmt.Println(k, "is an array:")
			for i, u := range vv {
				fmt.Println(i, u)
			}
		default:
			fmt.Println(k, "is of a type I don’t know how to handle")
		}
	}

	fmt.Printf("f data %s \n", f)
	fmt.Printf("m data %s \n", m)
}

/*
 * 生成json案例2
 */
func Example2() {

	fmt.Println("生成json案例2")

	pa := &Address{"private", "Aartselaar", "Belgium"}
	wa := &Address{"work", "Boom", "Belgium"}
	vc := VCard{"Jan", "Kersschot", []*Address{pa, wa}, "none"}

	// JSON format:
	js, _ := json.Marshal(vc)

	fmt.Printf("%s", js)
}
